package com.bsj.travel.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsj.travel.def.common.DTO.web.monitor.SysJobDTO;
import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.def.monitor.job.SysJob;
import com.bsj.travel.mapper.mysql.SysJobMapper;
import com.bsj.travel.monitor.service.SysJobService;
import com.bsj.travel.monitor.utils.CronUtils;
import com.bsj.travel.monitor.utils.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 定时任务调度实现
 * @date 2024/1/23
 */
@Service
@Slf4j
public class SysJobServiceImpl implements SysJobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper sysJobMapper;

    /**
     * 项目自启动，初始化定时器，防止手动修改数据库导致未同步定时任务处理(注： 不能手动修改主键ID和任务组名，否则会有脏数据)
     * @throws SchedulerException
     */
    @PostConstruct
    public void init() throws SchedulerException {
        scheduler.clear();
        List<SysJob> jobList = sysJobMapper.selectAllJob();
        jobList.stream().forEach(item -> {
            try {
                ScheduleUtils.createScheduleJob(scheduler, item);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
    }


    /**
     * 根据条件获取quartz调度器的计划任务列表
     * @param sysJob
     * @return
     */
    @Override
    public List<SysJob> selectJobList(SysJob sysJob) {
        return sysJobMapper.selectJobList(sysJob);
    }

    /**
     * 根据条件获取quartz调度器的计划任务列表(分页)
     * @param dto
     * @return
     */
    @Override
    public JsonResult<List<SysJob>> selectJobPageList(SysJobDTO dto) {
        int total = 0;
        IPage<SysJob> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        QueryWrapper<SysJob> queryWrapper = new QueryWrapper<>();
        if (dto.getJobName() != null) {
            queryWrapper.like("jobName", dto.getJobName());
        }
        if (dto.getJobGroup() != null) {
            queryWrapper.eq("jobGroup", dto.getJobGroup());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq("status", dto.getStatus());
        }
        if (dto.getInvokeTarget() != null) {
            queryWrapper.like("invokeTarget", dto.getInvokeTarget());
        }
        IPage<SysJob> sysJobIPage = sysJobMapper.selectPage(page, queryWrapper);
        total = (int) sysJobIPage.getTotal();
        return JsonResult.success(sysJobIPage.getRecords(), total);
    }

    /**
     * 通过调度任务ID查询定时任务
     * @param jobId 主键ID
     * @return
     */
    @Override
    public SysJob selectJobById(Long jobId) {
        return sysJobMapper.selectById(jobId);
    }

    /**
     * 暂停任务
     * @param job 调度信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int pauseJob(SysJob job) throws Exception{
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(1);
        int rows = sysJobMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws Exception {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(0);
        int rows = sysJobMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将删除
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws Exception {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = sysJobMapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     * @param jobIds 需要删除的任务ID
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(List<Long> jobIds) throws Exception {
        for (Long jobId : jobIds) {
            SysJob job = sysJobMapper.selectById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws Exception {
        int rows = 0;
        int status = job.getStatus();
        if (status == 0) {
            rows = resumeJob(job);
        } else if (status == 1) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 定时任务立即执行
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJob job) throws Exception {
        boolean result = false;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(jobId);
        //参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleUtils.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws Exception {
        int rows = sysJobMapper.insert(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务
     * @param job 调度信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws Exception {
        SysJob sysJob = selectJobById(job.getJobId());
        int rows = sysJobMapper.updateById(job);
        if (rows > 0) {
            updateSchedulerJob(job, sysJob.getJobGroup());
        }
        return rows;
    }

    /**
     * 检验cron表达式是否有效
     * @param cronExpression 表达式
     * @return
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }

    /**
     * 更新任务
     * @param job 任务对象
     * @param jobGroup 任务组
     * @throws Exception
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws Exception {
        Long jobId = job.getJobId();
        //判断调度任务是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
}
